package com.vader.admin.service.impl;

import com.vader.admin.client.DistributeIdClient;
import com.vader.admin.dao.BaseGroupInfoDao;
import com.vader.admin.entity.DO.BaseGroupInfo;
import com.vader.admin.service.BaseGroupInfoService;
import com.vader.common.entity.CommonResponse;
import com.vader.common.exception.BadRequestException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author Vader
 * @date 2021/10/6
 **/
@Service
public class BaseGroupInfoServiceImpl implements BaseGroupInfoService {
    @Resource
    private BaseGroupInfoDao baseGroupInfoDao;
    @Resource
    private DistributeIdClient distributeIdClient;

    @Override
    public BaseGroupInfo queryById(Long id) {
        return baseGroupInfoDao.queryById(id);
    }

    @Override
    public Page<BaseGroupInfo> queryByPage(BaseGroupInfo baseGroupInfo, PageRequest pageRequest) {
        long total = baseGroupInfoDao.count(baseGroupInfo);
        return new PageImpl<>(this.baseGroupInfoDao.queryAllByLimit(baseGroupInfo, pageRequest), pageRequest, total);
    }

    @Override
    public BaseGroupInfo insert(BaseGroupInfo baseGroupInfo) {
        CommonResponse<Long> id = distributeIdClient.getId();
        if (id.getCode() != 0) {
            throw new BadRequestException("生成组织di异常");
        }
        baseGroupInfo.setId(id.getData());
        baseGroupInfoDao.insert(baseGroupInfo);
        return baseGroupInfo;
    }

    @Override
    public BaseGroupInfo update(BaseGroupInfo baseGroupInfo) {
        baseGroupInfoDao.update(baseGroupInfo);
        return baseGroupInfo;
    }

    @Override
    public boolean deleteById(Long id) {
        BaseGroupInfo baseGroupInfo = baseGroupInfoDao.queryById(id);
        if (Objects.isNull(baseGroupInfo)) {
            throw new BadRequestException("组织不存在");
        }
        baseGroupInfo.setIsDeleted(1);
        return baseGroupInfoDao.update(baseGroupInfo) > 0;
    }
}
